<template>
  <div>
    <div>
      <van-nav-bar class="page-nav-bar" title="登录" left-arrow />

      <van-form @submit="onSubmit">
        <!-- 思考：在组件里插入不同的dom元素 -->
        <!-- vant已经告诉我们插槽的名字 -->
        <van-field
          v-model="user.mobile"
          placeholder="手机号"
          name="手机号"
          :rules="userValidatorPhone"
        >
          <template #left-icon>
            <span class="toutiao toutiao-shouji"></span>
          </template>
        </van-field>
        <van-field
          v-model="user.code"
          placeholder="验证码"
          name="验证码"
          :rules="userValidatorCode"
        >
          <template #left-icon>
            <span class="toutiao toutiao-yanzhengma"></span>
          </template>
          <template #button>
            <van-button class="send-sms-btn" round size="mini" type="default">
              获取验证码
            </van-button>
          </template>
        </van-field>
        <div style="margin: 16px">
          <van-button block round type="info" native-type="submit">
            登录
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>
<script>
//按需引入 loginapi 封装的
import { loginApi } from "@/api/login";
import { Toast } from "vant";
// import { setItem } from "@/utils/storage";

export default {
  data() {
    return {
      // username: "",
      // password: "",
      // mobile: "",
      // code: "",
      user: {
        mobile: "",
        code: "",
      },
      userValidatorPhone: [
        { required: true, message: "请填手机号" },
        { pattern: /^1[3|5|7|8]\d{9}$/, message: "请输入正确的手机号" },
      ],
      userValidatorCode: [
        { required: true, message: "请输入验证码" },
        { pattern: /^\d{6}$/, message: "请输入正确的验证码" },
      ],
    };
  },
  methods: {
    async onSubmit() {
      // let obj = {
      //   mobile: this.mobile,
      //   code: this.code,
      // };

      Toast.loading({
        forbidClick: true,
        message: "登录中..",
        duration: 0,
      });
      //判断输入的是不是空
      // if (this.user.mobile != "" && this.user.code != "") {
      try {
        let { data } = await loginApi(this.user);

        // setItem("token", data.data.token);
        this.$store.commit("setToken", data.data.token);
        this.$store.commit("setRefreshToken", data.data.refresh_token);
        Toast.success("登录成功");
        //登录成功之后 返回上一级界面 也就是我的界面
        this.$router.back();
      } catch (error) {
        Toast.fail(error.response.data.message);
      }
      // let res = await loginApi(this.user);
      // if (res.data.message == "OK") {
      //   Toast.success("登录成功");
      // } else {
      //   Toast.fail(res.data.data.message);
      // }
      //
    },
  },
};
</script>
<style scoped>
.toutiao {
  font-size: 37px;
}
.send-sms-btn {
  width: 152px;
  height: 46px;
  line-height: 46px;
  background-color: #ededed;
  font-size: 22px;
  color: #666;
}
</style>
